package com.example.game_community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.game_community.entity.*;
import com.example.game_community.mapper.PostMapper;
import com.example.game_community.service.*;
import com.example.game_community.utils.Result;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.UUID;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    @Autowired
    private PostImageService postImageService;

    @Value("${app.storage.final}")
    private String finalPath;

    @Value("${app.storage.temp}")
    private String tempDir;

    /**
     * 获取详情贴子
     */
    @Override
    public Result<Post> getPostDetail(Long postId) {
        // 1. 查询帖子基本信息
        Post post = this.getById(postId);
        if (post == null) {
            return Result.error("贴子不存在");
        }

        // 2. 查询关联的图片
        List<PostImage> images = postImageService.list(
                new LambdaQueryWrapper<PostImage>()
                        .eq(PostImage::getPostId, postId)
        );

        // 3. 设置图片URL列表
        post.setImageUrls(images.stream()
                .map(PostImage::getImageUrl)
                .collect(Collectors.toList()));

        // 4. 查询作者信息
        if (post.getAuthorId() != null) {
            post.setUserInfo(userService.getById(post.getAuthorId()));
        }

        return Result.success(post);
    }


    /**
     * 处理并移动临时图片到永久目录
     */
    private String processAndMoveImages(String htmlContent) {
        Document doc = Jsoup.parse(htmlContent);
        Elements imgTags = doc.select("img[src^='http://localhost:8082/temp-images/']");

        for (Element img : imgTags) {
            String tempUrl = img.attr("src");
            try {
                // 生成永久文件名
                String tempFilename = tempUrl.substring(tempUrl.lastIndexOf('/') + 1);
                String finalFilename = tempFilename.replace("temp-", "final-");

                // 移动文件
                Path source = Paths.get(tempDir, tempFilename);
                Path target = Paths.get(finalPath, finalFilename);
                Files.createDirectories(target.getParent());
                Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

                // 更新图片URL
                String finalUrl = "http://localhost:8082/images/" + finalFilename;
                img.attr("src", finalUrl);
            } catch (IOException e) {
                // 处理异常，记录日志
                System.err.println("移动图片失败: " + e.getMessage());
            }
        }
        return doc.body().html();
    }

    /**
     * 创建帖子 (正式保存图片)
     */

    @Override
    public Result<Post> createPost(Post post) {
        // 处理内容中的图片
        String processedContent = processAndMoveImages(post.getContent());
        post.setContent(processedContent);

        // 1. 设置帖子基本信息
        post.setCreateTime(LocalDateTime.now());
        // 2. 保存帖子到数据库
        baseMapper.insert(post);

        return Result.success(post);
    }

    /**
     * 获取临时图片URL (用于预览)
     */
    @Override
    public Result<String> getTempImgUrls(MultipartFile file) throws IOException {
        if (!Objects.requireNonNull(file.getContentType()).startsWith("image/")) {
            return Result.error("仅支持图片文件");
        }

        // 生成唯一文件名: UUID + 原始文件名
        String fileName = "temp-" + UUID.randomUUID() + "_" + file.getOriginalFilename();
        Path tempPath = Paths.get(tempDir, fileName);

        // 确保目录存在
        Files.createDirectories(tempPath.getParent());
        // 保存临时文件
        Files.copy(file.getInputStream(), tempPath, StandardCopyOption.REPLACE_EXISTING);

        // 返回临时访问URL
        String tempUrl = "http://localhost:8082/temp-images/" + fileName;
        return Result.success(tempUrl);
    }


    // 增加评论
    @Override
    public Result<Comment> createComment(Long postId, Comment comment) {
        String processedContent = processAndMoveImages(comment.getContent());
        comment.setContent(processedContent);
        comment.setUserId(comment.getUserId());
        comment.setPostId(postId);
        comment.setCommentTime(LocalDateTime.now());

        commentService.save(comment);
        return Result.success("评论成功");
    }

    @Override
    public Result<Page<Post>> getAllPost(int current, int size) {
        // 创建分页对象
        Page<Post> page = new Page<>(current, size);

        // 分页查询，添加排序条件
        this.page(page, new LambdaQueryWrapper<Post>().orderByDesc(Post::getCreateTime));

        // 如果查询结果为空
        if (page.getRecords().isEmpty()) {
            return Result.error("没有帖子数据");
        }

        // 获取所有帖子ID和作者ID
        Set<Long> postIds = page.getRecords().stream().map(Post::getId).collect(Collectors.toSet());
        Set<Long> authorIds = page.getRecords().stream().map(Post::getAuthorId).collect(Collectors.toSet());

        // 批量查询用户信息
        Map<Long, User> userMap = userService.listByIds(authorIds).stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));

        // 批量查询帖子图片
        Map<Long, List<PostImage>> postImagesMap = postImageService.list(
                new LambdaQueryWrapper<PostImage>()
                        .in(PostImage::getPostId, postIds)
        ).stream().collect(Collectors.groupingBy(PostImage::getPostId));

        // 绑定用户信息和图片到帖子
        page.getRecords().forEach(post -> {
            // 设置用户信息
            post.setUserInfo(userMap.get(post.getAuthorId()));

            // 设置图片URL列表
            List<PostImage> images = postImagesMap.getOrDefault(post.getId(), Collections.emptyList());
            post.setImageUrls(images.stream()
                    .map(PostImage::getImageUrl)
                    .collect(Collectors.toList()));
        });

        return Result.success(page);
    }

    // 获取每个用户发布的贴子
    @Override
    public Result<List<Post>> getUserPostDetail(Long userId) {
        List<Post> postList = this.list(new LambdaQueryWrapper<Post>().eq(Post::getAuthorId, userId));
        if (postList.isEmpty()) {
            return Result.error("该用户没有发布过帖子");
        }

        // 绑定用户信息
        User user = userService.getById(userId);
        postList.forEach(post -> post.setUserInfo(user));

        return Result.success(postList);
    }

}
